const mongoose = require('mongoose');

// 审计日志模型定义
const auditLogSchema = new mongoose.Schema({
  action: {
    type: String,
    required: true,
    trim: true,
    index: true
  },
  entityType: {
    type: String,
    required: true,
    trim: true,
    index: true
  },
  entityId: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  },
  entityName: {
    type: String,
    trim: true
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    index: true
  },
  userName: {
    type: String,
    trim: true
  },
  userRole: {
    type: String,
    trim: true,
    index: true
  },
  ipAddress: {
    type: String,
    trim: true
  },
  userAgent: {
    type: String,
    trim: true
  },
  details: {
    type: mongoose.Schema.Types.Mixed
  },
  timestamp: {
    type: Date,
    default: Date.now,
    required: true,
    index: true
  }
});

// 创建复合索引以提高常见查询的性能
auditLogSchema.index({ userId: 1, timestamp: -1 });
auditLogSchema.index({ entityType: 1, entityId: 1 });
auditLogSchema.index({ action: 1, timestamp: -1 });
auditLogSchema.index({ userRole: 1, timestamp: -1 });

// 静态方法：记录操作日志
auditLogSchema.statics.logAction = async function(logData) {
  try {
    const log = new this({
      action: logData.action,
      entityType: logData.entityType,
      entityId: logData.entityId,
      entityName: logData.entityName,
      userId: logData.userId,
      userName: logData.userName,
      userRole: logData.userRole,
      ipAddress: logData.ipAddress,
      userAgent: logData.userAgent,
      details: logData.details,
      timestamp: new Date()
    });
    
    return await log.save();
  } catch (error) {
    console.error('审计日志记录失败:', error);
    // 不抛出错误，避免影响主要功能
    return null;
  }
};

// 静态方法：获取用户操作历史
auditLogSchema.statics.getUserActions = async function(userId, limit = 50, offset = 0) {
  return await this.find({ userId })
    .sort({ timestamp: -1 })
    .limit(limit)
    .skip(offset);
};

// 静态方法：获取实体操作历史
auditLogSchema.statics.getEntityHistory = async function(entityType, entityId, limit = 50) {
  return await this.find({ entityType, entityId })
    .sort({ timestamp: -1 })
    .limit(limit);
};

// 静态方法：获取操作统计
auditLogSchema.statics.getActionStats = async function(startDate, endDate) {
  const query = {};
  if (startDate) {
    query.timestamp = { $gte: startDate };
  }
  if (endDate) {
    query.timestamp = query.timestamp || {};
    query.timestamp.$lte = endDate;
  }
  
  return await this.aggregate([
    { $match: query },
    {
      $group: {
        _id: { action: '$action', userRole: '$userRole' },
        count: { $sum: 1 }
      }
    },
    { $sort: { '_id.action': 1, '_id.userRole': 1 } }
  ]);
};

const AuditLog = mongoose.model('AuditLog', auditLogSchema);

module.exports = AuditLog;